<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const user = useUserStore()

const form = reactive({ username: '', password: '' })
const loading = reactive({ submitting: false })
const formRef = ref()

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '至少 3 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '至少 6 位密码', trigger: 'blur' }
  ]
}

const onSubmit = async () => {
  await formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    loading.submitting = true
    const ok = await user.login(form.username, form.password)
    loading.submitting = false
    if (ok) {
      const redirect = (route.query.redirect as string) || '/'
      router.replace(redirect)
    } else {
      // 简单错误提示
      alert('用户名或密码错误')
    }
  })
}
</script>

<template>
  <div class="login">
    <el-card class="card">
      <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px">
        <h2 style="margin:0">登录</h2>
      </div>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" @keyup.enter.native="onSubmit">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="current-password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading.submitting" :disabled="loading.submitting" @click="onSubmit">登录</el-button>
          <router-link to="/register" style="margin-left:8px">
            <el-button :disabled="loading.submitting">注册</el-button>
          </router-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  
</template>

<style scoped>
.login { display:flex; align-items:center; justify-content:center; height:100vh; }
.card { width:360px; }
</style>


